<?php

if (!defined('APP') or !constant('APP')) die('Direct access not allowed!');
ini_set('display_errors', 1); 
ini_set('log_errors', 1); 


class DemotModel {
    public static $sort = array(
      'SORT_STATUS_ASC' => 1,  
      'SORT_STATUS_DESC' => 2,
      'SORT_DATE_DESC' => 3,
      'SORT_DATE_ASC' => 4
    );
    
    public static function rank($id, $mode)
    {
        $query = "SELECT rank, rank_minus, rank_plus FROM `demots` WHERE id = :id;";
        $result = DB::getPDO()->prepare($query);
        $result->execute(array(
            ':id' => intval($id)     
            ));  
        $result = $result->fetch();
        
        if (sizeof($result) < 1) { return false; }
        
        $rank = 0;
        $rank_minus = intval($result['rank_minus']);
        $rank_plus = intval($result['rank_plus']);
        
        switch($mode)
        {
            case "minus": 
                $rank = intval($result['rank']) - 1; 
                $rank_minus++;
                break;
            default: 
                $rank = intval($result['rank']) +1;
                $rank_plus++;
        }
        
        $query = "UPDATE `demots` SET `rank`=:rank, `rank_plus`=:rank_plus, `rank_minus`=:rank_minus WHERE `id`=:id";   
      
        $data[':id'] = intval($id);
        $data[':rank'] = $rank;
        $data[':rank_plus']  = $rank_plus;
        $data[':rank_minus'] = $rank_minus;
              
        $result = DB::getPDO()->prepare($query);
        
        $result->execute($data);  
    }
    
    public static function isDemotUser($id_demot)
    {
        $query = "SELECT id FROM `demots` WHERE id = :id AND id_user = :id_user;";
        $result = DB::getPDO()->prepare($query);
        $result->execute(array(
            ':id' => intval($id_demot),
            ':id_user' => intval(UserModel::isLoggedIn()),
            ));  
        $result = $result->fetchAll();
        
        if (sizeof($result) < 1) { return false; }
        
        return true;  
    }
    
    public static function update($request)
    {   
        $data = array();
       
        $data[':id'] = isset($request['id']) ? intval($request['id']) : 0;
        
        if ($data[':id']==0) return false;
        
        $data[':id_category'] = isset($request['id_category']) ? intval($request['id_category']) : 0;
        $data[':id_statuses'] = isset($request['id_statuses']) ? intval($request['id_statuses']) : 0;
        $data[':title'] = isset($request['title']) ? htmlspecialchars($request['title']) : "Bład w tytule";
        $data[':img'] = isset($request['img']) ? $request['img'] : "default.jpg";
        $data[':id_type'] = isset($request['id_type']) ? $request['id_type'] : "";
        $data[':for_adults'] = isset($request['for_adults']) ? (($request['for_adults']=="on") ? 1 : 0 ) : 0;
        
        $query = "UPDATE `demots` SET `id_user`=:id_user, `for_adults`=:for_adults, `id_category`=:id_category, 
            `is_active`=:is_active, `title`=:title, `id_type`=:id_type, `id_statuses`=:id_statuses, `img`=:img, `rank`=:rank WHERE `id`=:id";   
         
        $data[':id_user'] = intval(UserModel::isLoggedIn());
        $data[':rank'] = 0;
        
        $data[':is_active'] = isset($request['is_active']) ? ($request['is_active']=="on" ?  1 : 0) : 0;
        $data[':img'] = '1.png'; //fake
       
        $result = DB::getPDO()->prepare($query);
        
        $result->execute($data);            
    }
    
    public static function changeStatus($id, $id_statuses)
    {           
        $data = array('id' => $id, 'id_statuses' => $id_statuses);
        
        $query = "UPDATE `demots` SET `id_statuses`=:id_statuses WHERE `id`=:id";   
                  
        $result = DB::getPDO()->prepare($query);
        
        $result = $result->execute($data);                    
       
        return $result;
    }

    public static function updateByUser($request, $id_type = DStatus::TYPE_IMAGE)
    {   
        $data = array();
        $data[':id'] = isset($request['id']) ? intval($request['id']) : 0;
        
        if ($data[':id']==0) return false;
        
        if (!self::isDemotUser($data[':id'])) return false;
        
        $data[':id_category'] = isset($request['id_category']) ? intval($request['id_category']) : 0;
        $data[':title'] = isset($request['title']) ? htmlspecialchars($request['title']) : "Bład w tytule";
        $data[':movie'] = isset($request['movie']) ? $request['movie'] : "";
        $data[':for_adults'] = isset($request['for_adults']) ? (($request['for_adults']=="on") ? 1 : 0 ) : 0;
              
        $query = "UPDATE `demots` SET `movie`=:movie, `for_adults`=:for_adults, `id_user`=:id_user, `id_category`=:id_category, 
            `is_active`=:is_active, `id_type`=:id_type, `id_statuses`=:id_statuses, `title`=:title WHERE `id`=:id";   
         
        $data[':id_statuses'] = DStatus::QUEUE; //!warn
        $data[':id_type'] = intval($id_type);
        $data[':id_user'] = intval(UserModel::isLoggedIn());   
        $data[':is_active'] = 1; //!warn
         
        $result = DB::getPDO()->prepare($query);
        
        $result = $result->execute($data);                    
       
        return $result;
    }
    
    public static function save($request = null, $status = DStatus::FRESH)
    {
        $data = array();
        $data[':id_category'] = isset($request['id_category']) ? intval($request['id_category']) : 0;
        $data[':title'] = isset($request['title']) ? $request['title'] : "";
        $data[':movie'] = isset($request['movie']) ? $request['movie'] : "";
        $data[':img'] = isset($request['img']) ? $request['img'] : "default.jpg";
        $data[':for_adults'] = isset($request['for_adults']) ? (($request['for_adults']=="on") ? 1 : 0 ) : 0;
        
        //zabezp.!!!       
        $data[':id_statuses'] = isset($request['id_statuses']) ? $request['id_statuses'] : $status;
                
        $query = "INSERT INTO `demots` (`for_adults`, `id_type`, `movie`, `id_user`, `id_category`, `is_active`, `title`, `img`, `rank`,`id_statuses`)
            VALUES (:for_adults, :id_type, :movie, :id_user, :id_category, :is_active, :title, :img, :rank, :id_statuses);";
        
        $data[':id_user'] = intval(UserModel::isLoggedIn());
        $data[':rank'] = 0;
        $data[':is_active'] = 0;
        $data[':id_type'] = DStatus::TYPE_IMAGE;
        $data[':img'] = '1.png'; //fake
       
        $result = DB::getPDO()->prepare($query);
       
        $result = $result->execute($data); 
        $result = DB::getPDO()->lastInsertId();
        return $result;
    }
    
    public static function fetch($id)
    {
        $data = array(":id" => intval($id));
        $query = "SELECT * FROM `demots` WHERE id = :id ORDER by date DESC";
        $result = DB::getPDO()->prepare($query);
        $result->execute($data);  
        $result = $result->fetch();
        return $result;
    }
    
    public static function countAdminAll()
    {
        $query = "SELECT COUNT(*) FROM `demots`";
        $result = DB::getPDO()->prepare($query);
        $result->execute();  
        $result = $result->fetch();
        
        if (sizeof($result) < 1) { return 0; }

        return $result['COUNT(*)'];   
    }
    
    public static function countOrderBy($id_filter = DStatus::FILTER_TOP)
    {
        $filter ="";
        
        switch ($id_filter)
        {
            case DStatus::FILTER_TOP: $filter = "AND rank>100"; break;
        }
        
        $query = "SELECT COUNT(*) FROM `demots` WHERE id_statuses = :id_statuses AND is_active=1 ".$filter;
        $result = DB::getPDO()->prepare($query);
        $result->execute(array(
            ':id_statuses' => DStatus::NORMAL     
            ));  
        $result = $result->fetch();
        
        if (sizeof($result) < 1) { return 0; }

        return $result['COUNT(*)'];   
    }
    
    public static function countByCategory($id_cat)
    {
        $query = "SELECT COUNT(*) FROM `demots` WHERE id_statuses = :id_statuses AND id_category=:id_category AND is_active=1;";
        $result = DB::getPDO()->prepare($query);
        $result->execute(array(
            ':id_statuses' => DStatus::NORMAL,
            ':id_category' => intval($id_cat)            
            ));  
        $result = $result->fetch();
        
        if (sizeof($result) < 1) { return 0; }

        return $result['COUNT(*)'];   
    }
    
    public static function countByQuery($query_txt)
    {
        $query = "SELECT COUNT(*) FROM `demots` WHERE id_statuses = :id_statuses AND is_active=1 AND title LIKE :query;";
        $result = DB::getPDO()->prepare($query);
        $result->execute(array(
            ':id_statuses' => DStatus::NORMAL,
            ':query' => '%'.$query_txt.'%'
            ));  
        $result = $result->fetch();
        
        if (sizeof($result) < 1) { return 0; }

        return $result['COUNT(*)'];   
    }
    
    public static function count($id_statuses = DStatus::UNDEFINED)
    {
        $query = "SELECT COUNT(*) FROM `demots` WHERE id_statuses = :id_statuses AND is_active=1;";
        $result = DB::getPDO()->prepare($query);
        $result->execute(array(
            ':id_statuses' => intval($id_statuses)     
            ));  
        $result = $result->fetch();
        
        if (sizeof($result) < 1) { return 0; }

        return $result['COUNT(*)'];   
    }
    
    public static function exist($id)
    {
        $query = "SELECT id FROM `demots` WHERE id = :id;";
        $result = DB::getPDO()->prepare($query);
        $result->execute(array(
            ':id' => intval($id)     
            ));  
        $result = $result->fetchAll();
        
        if (sizeof($result) < 1) { return false; }
        
        return true;   
    }
        
    public static function fetchAllAdmin($start = -1, $limit = -1)            
    {        
        $strQuery = "";
        $data = array();
       
        $ssort = isset($_SESSION['sort']) ? $_SESSION['sort'] : "";
        $order='';
        
        switch($ssort):
            case self::$sort['SORT_STATUS_ASC']: $order = 'ORDER by `id_statuses` ASC'; break;
            case self::$sort['SORT_STATUS_DESC']: $order = 'ORDER by `id_statuses` DESC'; break;
            case self::$sort['SORT_DATE_DESC']: $order = 'ORDER by `date` DESC'; break;
            case self::$sort['SORT_DATE_ASC']: $order = 'ORDER by `date` ASC'; break;
            default: $order = "ORDER by `date` DESC";
        endswitch;
        
        if ($start == -1 || $limit == -1)
            $query = "SELECT * FROM `demots` ".$order." DESC";
        else            
            $query = "SELECT * FROM `demots` " . $order ." LIMIT :start, :limit";
   
    
        $result = DB::getPDO()->prepare($query);
   
        if ($start == -1 || $limit == -1)
        {            
            $result->execute();  
        }
        else
        {           
            $result->bindValue(':start', intval($start), PDO::PARAM_INT);
            $result->bindValue(':limit', intval($limit), PDO::PARAM_INT);
            $result->execute();
        }
        
        $result = $result->fetchAll();    
               
        return $result;
    }
    
    public static function fetchOrderBy($start = -1, $limit = -1, $filter_status_id)
    {
       $strQuery = "";
        $data = array();
        $id_statuses = DStatus::NORMAL;
        $strQuery = 'WHERE id_statuses=:id_statuses AND is_active=1';
        
        switch ($filter_status_id)
        {
            case DStatus::FILTER_TOP: $filter_name = "`rank` ASC"; $strQuery.=' AND rank>100'; break;            
            case DStatus::FILTER_RANDOM: $filter_name = "RAND()"; break;
            default: $filter_name = "`date` DESC";
        }
        
        
        if ($start == -1 || $limit == -1)
            $query = "SELECT * FROM `demots` ".$strQuery." ORDER BY ".$filter_name;
        else            
            $query = "SELECT * FROM `demots` ".$strQuery." ORDER BY ".$filter_name." LIMIT :start, :limit";
   
    
        $result = DB::getPDO()->prepare($query);
        
        if ($start == -1 || $limit == -1)
        {
            if ($strQuery!="")
                $result->bindValue(':id_statuses', $id_statuses);
            $result->execute();  
        }
        else
        {
            if ($strQuery!="")
                $result->bindValue(':id_statuses', $id_statuses);
            $result->bindValue(':start', intval($start), PDO::PARAM_INT);
            $result->bindValue(':limit', intval($limit), PDO::PARAM_INT);
            $result->execute();
        }
        
        $result = $result->fetchAll();    
        return $result; 
    }
    
     public static function fetchByCategory($start = -1, $limit = -1, $id_cat)
    {
        $strQuery = "";
        $data = array();
        $id_statuses = DStatus::NORMAL;
        $strQuery = 'WHERE id_statuses=:id_statuses AND id_category=:id_category AND is_active=1';
                
        $filter_name = "`date` DESC";
        
        if ($start == -1 || $limit == -1)
            $query = "SELECT * FROM `demots` ".$strQuery." ORDER BY ".$filter_name;
        else            
            $query = "SELECT * FROM `demots` ".$strQuery." ORDER BY ".$filter_name." LIMIT :start, :limit";
   
    
        $result = DB::getPDO()->prepare($query);
        $result->bindValue(':id_category', intval($id_cat), PDO::PARAM_INT);
        
        if ($start == -1 || $limit == -1)
        {
            if ($strQuery!="")
                $result->bindValue(':id_statuses', $id_statuses);
            $result->execute();  
        }
        else
        {
            if ($strQuery!="")
                $result->bindValue(':id_statuses', $id_statuses);
            $result->bindValue(':start', intval($start), PDO::PARAM_INT);
            $result->bindValue(':limit', intval($limit), PDO::PARAM_INT);
            $result->execute();
        }
        
        $result = $result->fetchAll();    
        return $result; 
    }
    
    public static function fetchByQuery($start = -1, $limit = -1, $query_txt)
    {
        $strQuery = "";
        $data = array();
        $id_statuses = DStatus::NORMAL;
        $id_statuses = "`id_statuses`=".  DStatus::NORMAL. " OR `id_statuses`=".DStatus::QUEUE;
        $strQuery = 'WHERE '.$id_statuses.' AND `title` LIKE :query';
                        
        $filter_name = "`date` DESC";
                        
        if ($start == -1 || $limit == -1)
            $query = "SELECT * FROM `demots` ".$strQuery." ORDER BY ".$filter_name;
        else            
            $query = "SELECT * FROM `demots` ".$strQuery." ORDER BY ".$filter_name." LIMIT :start, :limit";
       
        $result = DB::getPDO()->prepare($query);
                    
        $result->bindValue(':query', '%'.$query_txt.'%', PDO::PARAM_STR);        
        
        if ($start == -1 || $limit == -1)
        {
          
            $result->execute();  
        }
        else
        {
                     
            $result->bindValue(':start', intval($start), PDO::PARAM_INT);
            $result->bindValue(':limit', intval($limit), PDO::PARAM_INT);
            $result->execute();
        }
        
        $result = $result->fetchAll(); 
        //die(print_r($result));

        return $result; 
    }
    
    public static function fetchAll($start = -1, $limit = -1, $id_status = null)            
    {        
        $strQuery = "";
        $data = array();
        $id_statuses = DStatus::NORMAL;
        $strQuery = 'WHERE id_statuses=:id_statuses';
        
        if (DStatus::exist(intval($id_status)))
        {
            $id_statuses = intval($id_status);
            
        }
        
        if ($start == -1 || $limit == -1)
            $query = "SELECT * FROM `demots` ".$strQuery." ORDER by `date` DESC";
        else            
            $query = "SELECT * FROM `demots` ".$strQuery." ORDER BY date DESC LIMIT :start, :limit";
   
    
        $result = DB::getPDO()->prepare($query);
        
        if ($start == -1 || $limit == -1)
        {
            if ($strQuery!="")
                $result->bindValue(':id_statuses', $id_statuses);
            $result->execute();  
        }
        else
        {
            if ($strQuery!="")
                $result->bindValue(':id_statuses', $id_statuses);
            $result->bindValue(':start', intval($start), PDO::PARAM_INT);
            $result->bindValue(':limit', intval($limit), PDO::PARAM_INT);
            $result->execute();
        }
        
        $result = $result->fetchAll();    
        return $result;
    }
    
    public static function delete($id)
    {        
        $data = array(':id' => intval($id));
       
        $query = "DELETE FROM `demots` WHERE id = :id";
        $result = DB::getPDO()->prepare($query);
        $result->execute($data);  
        return $result;
    }
   
}

?>
